//
//  ClassScheduleViewController.m
//  iBaby365v2
//
//  Created by Kirinrin on 14-6-30.
//  Copyright (c) 2014年 suplus. All rights reserved.
//

#import "ClassScheduleViewController.h"
#import "ClassScheduleTitle.h"
#import "NetworkAccessManager.h"
#import "UIAlertView+Kirinrin.h"


#define kClassSchedulePreWeek   5

@interface ClassScheduleViewController ()
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@property (strong, nonatomic)NSArray *remoteData;


@end

@implementation ClassScheduleViewController{
    NSDateFormatter *dateFormater;
    NSCalendar *greCalendar;

}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    dateFormater = [[NSDateFormatter alloc] init];
    [dateFormater setDateFormat:@"YYYY-MM-dd EEEE"];
    greCalendar = [NSCalendar currentCalendar];
    
    [self setupScrollView];
    
    [self loadRemoteData];
    
}

- (void)viewWillAppear:(BOOL)animated{
    NSDateComponents *dateComponents = [greCalendar components:NSYearCalendarUnit | NSMonthCalendarUnit|NSWeekdayCalendarUnit|NSDayCalendarUnit fromDate:[NSDate date]];
    int weekday = dateComponents.weekday;
    if (weekday>1 && weekday<6) {
        int offsetX = weekday - 2;
        CGPoint point = CGPointMake(self.scrollView.frame.size.width*offsetX, 0);
        [self.scrollView setContentOffset:point];
    }else{
        [self.scrollView setContentOffset:CGPointZero];
    }

}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)loadRemoteData{
    NSString *uriString = [NSString stringWithFormat:@"ClassSchedule/%@/queryWeek.json", self.appDelegate.user[@"kClassId"] ];
    NSDictionary *parameters = @{@"key": self.appDelegate.accessKey};
    
    [[NetworkAccessManager shareManager]GET:uriString parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"opernation: %@\nresponse: %@", operation, responseObject);
        
        int resultCode = [responseObject[@"result"]intValue];
        if (resultCode == 0) {
            self.remoteData = responseObject[@"data"];
        }else{
            [UIAlertView alertWithRemoteError:resultCode];
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"opernation: %@\nerror: %@", operation, error);
        [UIAlertView alertWithNetworkError];
    }];
}

- (void)setupScrollView{
    CGRect bounds = [[UIScreen mainScreen] bounds];
    CGSize windowSize = bounds.size;
    int topViewHeight =[UIApplication sharedApplication].statusBarFrame.size.height + self.navigationController.navigationBar.frame.size.height;
    CGSize contentSize = CGSizeMake(windowSize.width * kClassSchedulePreWeek, windowSize.height - topViewHeight - 110);
    self.scrollView.contentSize = contentSize;
    
    
    for (int i = 0; i< kClassSchedulePreWeek; i++) {
        NSArray *nibViews=[[NSBundle mainBundle] loadNibNamed:@"ClassScheduleTitle" owner:self options:nil];
        ClassScheduleTitle *titleView = nibViews[0];
        CGRect tempFrame = titleView.frame;
        tempFrame.origin.x = windowSize.width * i;
        tempFrame.origin.y = 0;
        titleView.frame = tempFrame;
        
        NSDateComponents *dateComponents = [greCalendar components:NSYearCalendarUnit | NSMonthCalendarUnit|NSWeekdayCalendarUnit|NSDayCalendarUnit fromDate:[NSDate date]];
        [dateComponents setDay:dateComponents.day-(dateComponents.weekday - 2 )+i];
        NSDate *date = [greCalendar dateFromComponents:dateComponents];
        NSString *titleString =[dateFormater stringFromDate:date];
        titleView.titleLabel.text = titleString;
     
        
        [self.scrollView addSubview:titleView];
        
        CGRect subTableFrame = CGRectMake((windowSize.width * i) + 10, tempFrame.size.height, windowSize.width-20, windowSize.height - topViewHeight - tempFrame.size.height-10);
        UITableView *tempTable = [[UITableView alloc]initWithFrame:subTableFrame];
        tempTable.tag = i;
//        tempTable.backgroundColor = [UIColor redColor];
        tempTable.delegate = self;
        tempTable.dataSource = self;
        tempTable.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"28课程表-白底纹"]];
        [tempTable setSeparatorColor:UIColorFromRGB(0xfada94, 1.0)];
        
//        [tempTable registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
        [tempTable registerNib:[UINib nibWithNibName:@"ClassScheduleCellHeader" bundle:nil] forCellReuseIdentifier:@"ClassScheduleCellHeader"];
        [tempTable registerNib:[UINib nibWithNibName:@"ClassScheduleCell" bundle:nil] forCellReuseIdentifier:@"ClassScheduleCellRow"];
        [tempTable registerNib:[UINib nibWithNibName:@"ClassScheduleCellFooter" bundle:nil] forCellReuseIdentifier:@"ClassScheduleCellFooter"];
        [self.scrollView addSubview:tempTable];
        
    }

}

-(void)setRemoteData:(NSArray *)remoteData{
    _remoteData = remoteData;
    for (UIView *subView in self.scrollView.subviews) {
        if ([subView isKindOfClass:[UITableView class]]) {
            NSLog(@"tableview tag is %x", subView.tag);
            UITableView *view = (UITableView *)subView;
            [view reloadData];
        }
    }
    
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [self.remoteData[tableView.tag] count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell =nil;
    if (indexPath.row == 0) {
        cell = [tableView dequeueReusableCellWithIdentifier:@"ClassScheduleCellHeader"];
    }else if ( (indexPath.row +1) == [tableView numberOfRowsInSection:0]) {
        cell = [tableView dequeueReusableCellWithIdentifier:@"ClassScheduleCellFooter"];
    }else {
        cell = [tableView dequeueReusableCellWithIdentifier:@"ClassScheduleCellRow"];
    }
    
    
    NSDictionary *classScheduleForDay = [self.remoteData[tableView.tag] objectAtIndex:indexPath.row];
    
    NSArray *timeArray = [classScheduleForDay[@"time"] componentsSeparatedByString:@" "];
    
    UILabel *title = (UILabel *) [cell.contentView viewWithTag:101];
    [title setText: timeArray[0]];
    
    
    if (timeArray.count == 2) {
        UILabel *time = (UILabel *) [cell.contentView viewWithTag:102];
        [time setText: timeArray[1]];
    }
    
    
    UILabel *content = (UILabel *) [cell.contentView viewWithTag:103];
    [content setText: classScheduleForDay[@"name"]];
    
    
    return cell;
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 56;
}

@end
